package de.fhwgt.quiz.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import de.fhwgt.quiz.application.Player;
import de.fhwgt.quiz.application.Quiz;
import functions.QuickSorter;

/**
 * Servlet implementation class UserListServlet
 */
public class UserListServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private Quiz quiz;   

    /**
     * @throws ServletException 
     * @see HttpServlet#HttpServlet()
     */

	public UserListServlet() throws ServletException {
        super();
        this.quiz = Quiz.getInstance();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setHeader("pragma", "no-cache,no-store");  
        response.setHeader("cache-control", "no-cache,no-store,max-age=0,max-stale=0");  
        response.setCharacterEncoding("UTF-8");	   //To avoid the browser recognise our data as iso-8859-1
		response.setContentType("text/event-stream");
		PrintWriter out = response.getWriter();
		ArrayList<Player> playerlist;
		QuickSorter sorter = new QuickSorter();

		while(true){
			playerlist = new ArrayList<Player>();
			for(Player p : this.quiz.getPlayerList()){
				playerlist.add(p);
			}
			if(playerlist.size()>0)
				sorter.sort(playerlist);
			
			out.print("event: UserListRefresh\n");
			for(Player p : playerlist){
				out.print("data: "+p.getName()+";"+p.getScore()+";"+p.getId()+"\n");
			}
			if(this.quiz.getPlayerList().size()==0){
				out.print("data: No active players ...;;\n");											//returns nothing, this will JS make just an empty entry in the list
			}
			out.print("\n");
			out.flush();
			this.quiz.waitPlayerChange();

		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}
}


